package com.example.filter;

import cn.hutool.core.text.AntPathMatcher;
import com.example.config.AuthProperties;
import com.common.utils.JwtUtils;
import com.common.exception.UnauthorizedException;
import com.common.utils.CollUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@RequiredArgsConstructor
@Component
@EnableConfigurationProperties(AuthProperties.class)
public class AuthGlobalFilter implements GlobalFilter, Ordered{
    private final AuthProperties authProperties;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("过滤器执行咯咯咯咯咯咯咯咯");
        ServerHttpRequest request = exchange.getRequest();
        if(isExclude(request.getPath().toString())){
            System.out.println("放行咯咯咯咯咯咯");
            // 无需拦截，直接放行
            return chain.filter(exchange);
        }
        String token=null;
        List<String> headers = request.getHeaders().get("token");
        if(!CollUtils.isEmpty(headers))
        {
            token=headers.get(0);
        }
        System.out.println("token:::"+token);
        Long UserId=null;
        //开始校验并解析token
        try {
            UserId = JwtUtils.getUserId(token);
        }catch (UnauthorizedException e){
            //如果无效token，就拦截
           ServerHttpResponse response = exchange.getResponse();
            response.setRawStatusCode(401);
            return response.setComplete();
        }
        System.out.println("UserIDDDD:::::"+UserId);
        // TODO 如果有效，就存入用户身份信息
        System.out.println("存入用户信息");
        //传递用户信息
        String userInfo = UserId.toString();
        ServerWebExchange ex = exchange.mutate().request(b->b.header("userId",userInfo)).build();
        return chain.filter(ex);
    }

    @Override
    public int getOrder() {
        return 0;
    }
    private boolean isExclude(String antPath) {
        for (String pathPattern : authProperties.getExcludePaths()) {
            if(antPathMatcher.match(pathPattern, antPath)){
                return true;
            }
        }
        return false;
    }
}
